//package com.wmlt.file;
//
//import java.io.File;
//import java.io.IOException;
//import java.net.MalformedURLException;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.nio.file.StandardCopyOption;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.List;
//
//import org.apache.commons.codec.digest.DigestUtils;
//import org.apache.commons.lang3.ArrayUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.io.Resource;
//import org.springframework.core.io.UrlResource;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//import org.springframework.web.multipart.MultipartFile;
//
//import com.cgv.api.config.FileProperties;
//import com.cgv.api.em.FileType;
//import com.cgv.api.utils.JsonUtil;
//import com.cgv.api.utils.MimeTypeUtil;
//import com.cgv.api.web.rest.errors.BadRequestAlertException;
//
//
///**
// * create by huangziqideveloper@gmail.com
// */
//@Service
//public class FileService {
//
//	private static final Logger log = LoggerFactory.getLogger(FileService.class);
//
//	private static final String MIME_TYPE_IMAGE = "image";
//	private static final String MIME_TYPE_VIDEO = "video";
//	private static final String MIME_TYPE_MULTI = "multipart/form-data";
//
//	private static List<FileType> mimeTypeWhiteList = new ArrayList<FileType>();
//
////	private static FileType[] mimeTypeWhites = {FileType.JPEG};
//
//	static {
//		// 图片
//		mimeTypeWhiteList.add(FileType.JPEG);
//		mimeTypeWhiteList.add(FileType.PNG);
//		mimeTypeWhiteList.add(FileType.PNG2);
//		mimeTypeWhiteList.add(FileType.GIF);
//		mimeTypeWhiteList.add(FileType.BMP);
//		// 视频
//		mimeTypeWhiteList.add(FileType.MP4);
//		mimeTypeWhiteList.add(FileType.MPEG1);
//		mimeTypeWhiteList.add(FileType.MPEG2);
//		mimeTypeWhiteList.add(FileType.WAV);
//		mimeTypeWhiteList.add(FileType.AVI);
//		mimeTypeWhiteList.add(FileType.RAM);
//		mimeTypeWhiteList.add(FileType.RM);
//		mimeTypeWhiteList.add(FileType.ASF);
//	}
//
////	private static final String[] mimeTypeWhiteList = {
////				 "image/jpeg"
////				,"image/gif"
////				,"image/png"
////				,"image/bmp"
////				,"video/vnd.mpegurl"
////				,"video/x-m4v"
////				,"video/quicktime"
////				,"video/mpeg"
////				,"video/mp4"
////			};
//
//	@Autowired
//	private FileProperties fileProperties;
//
//	private final Path fileStorageLocation; // 文件在本地存储的地址
//
//    @Autowired
//    public FileService(FileProperties fileProperties) {
//    	log.info("上传路径:==>>{}", fileProperties.getImagePath());
//        this.fileStorageLocation = Paths.get(fileProperties.getImagePath()).toAbsolutePath().normalize();
//        try {
//            Files.createDirectories(this.fileStorageLocation);
//        } catch (Exception ex) {
//            throw new BadRequestAlertException("", "文件保存路径", "");
//        }
//    }
//
//    /**
//     * 保存
//     *
//     * @param file 文件
//     * @return 文件名
//     */
//    public String storeFile(MultipartFile file) {
//        // Normalize file name
//        String extension = getExt(file.getOriginalFilename());
//        String fileName = System.currentTimeMillis() + extension;
//        //String fileName =  StringUtils.cleanPath(file.getOriginalFilename());
//
//
//        try {
//            // Check if the file's name contains invalid characters
//            if(fileName.contains("..")) {
//            	throw new BadRequestAlertException("", "文件保存路径", "");
//            }
//
//            // Copy file to the target location (Replacing existing file with the same name)
//            Path targetLocation = this.fileStorageLocation.resolve(fileName);
//            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
//
//            return fileName;
//        } catch (IOException ex) {
//        	throw new BadRequestAlertException("", "文件保存路径", "");
//        }
//    }
//
//    /**
//     * 保存
//     * @param file
//     * @param path
//     * @return
//     */
//    public String storeFile(MultipartFile file, String path) {
//        // Normalize file name
//    	checkFile(file);
//        String extension = getExt(file.getOriginalFilename());
//        String fileName = "";
//        try {
//            fileName = DigestUtils.md5Hex(file.getInputStream())+ extension;
//        }catch (IOException e){
//            log.error("上传文件未找到");
//        }
//        log.debug("contentType:==>>>{}", JsonUtil.bean2Json(file.getContentType()));
//        log.debug("fileSize:==>>>{}", file.getSize());
//
//        try {
//            // Check if the file's name contains invalid characters
//            if(fileName.contains("..")) {
//            	throw new BadRequestAlertException("非法文件名", "出现系统错误", "999");
//            }
//
//            // Copy file to the target location (Replacing existing file with the same name)
//            Path targetLocation = this.fileStorageLocation.resolve(path != null ? path : "");
//            File destDir = targetLocation.toFile();
//            if(!(destDir.exists() && destDir.isDirectory())) {
//                destDir.mkdirs();
//            }
//            Files.copy(file.getInputStream(), targetLocation.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);
//
//
//            return fileName;
//        } catch (IOException ex) {
//        	throw new BadRequestAlertException("出现系统错误\n" +ex.getMessage(), "出现系统错误", "999");
//        }
//    }
//
//    /**
//     * 上传验证
//	 * @param file
//	 */
//	private void checkFile(MultipartFile file) {
//
//		mimeTypeCheck(file);
//
//		checkSize(file);
//
//	}
//
//	/**
//	 * 验证文件大小
//	 * @param file
//	 */
//	private void checkSize(MultipartFile file) {
//
//		String contentType = this.getMimeType(file);
//
//		if(contentType == null) throw new BadRequestAlertException("获取不到文件类型", "出现系统错误", "999");
//
//		long size = file.getSize();
//
//		if(contentType.indexOf(MIME_TYPE_IMAGE) > -1) {
//			if(size > fileProperties.getImageMaxSize()) {
//				log.error("possible max size:==>>>{}", fileProperties.getImageMaxSize());
//				log.error("file size:==>>>{}", size);
//				throw new BadRequestAlertException("超过图片文件大小限制", "出现系统错误", "999");
//			}
//		} else if(contentType.indexOf(MIME_TYPE_VIDEO) > -1) {
//			if(size > fileProperties.getVideoMaxSize()) {
//				log.error("possible max size:==>>>{}", fileProperties.getImageMaxSize());
//				log.error("file size:==>>>{}", size);
//				throw new BadRequestAlertException("超过视频文件大小限制", "出现系统错误", "999");
//			}
//		} else {
//			if(size > fileProperties.getVideoMaxSize()) {
//				log.error("possible max size:==>>>{}", fileProperties.getMaxSize());
//				log.error("file size:==>>>{}", size);
//				throw new BadRequestAlertException("超过文件大小限制", "出现系统错误", "999");
//			}
//		}
//
//	}
//
////	/**
////     * 验证mimeType
////     * @param file
////     */
////    public void mimeTypeCheck2(MultipartFile file){
////        if (file.isEmpty()){
////            throw new BadRequestAlertException(ErrorCodeEnum.FILE_IS_NULL);
////        }
////
////        FileType fileType = null;
////        try {
////			fileType = MimeTypeUtil.getFileType(file.getInputStream());
////		} catch (IOException e) {
////			log.error("failed in getInputStream.", e);
////		}
////
////        boolean anyMatch = mimeTypeWhiteList.contains(fileType);
////
////        if(!anyMatch) {
////        	log.error("mime type white list:{}", JsonUtil.bean2Json(mimeTypeWhiteList));
////        	log.error("upload mimeType:{}", JsonUtil.bean2Json(fileType));
////        	throw new BadRequestAlertException(ErrorCodeEnum.FILE_MIME_TYPE_INVALID);
////        }
////
////    }
//
//	/**
//     * 验证mimeType
//     * @param multipartFile
//     */
//    public void mimeTypeCheck(MultipartFile multipartFile){
//        if (multipartFile.isEmpty()){
//        	throw new BadRequestAlertException("参数中找不到文件", "出现系统错误", "999");
//        }
//        try {
//            String mimeType = this.getMimeType(multipartFile);
//            // 白名单
//            String[] whiteList = ArrayUtils.addAll(fileProperties.getMimeTypeImageWhiteList(), fileProperties.getMimeTypeVideoWhiteList());
//
//            boolean anyMatch = Arrays.stream(whiteList).anyMatch(x -> x.equalsIgnoreCase(mimeType));
//
//            if(!anyMatch) {
//            	log.error("mimeTypeCheck > mime type white list:{}", JsonUtil.bean2Json(whiteList));
//            	log.error("mimeTypeCheck > upload mimeType:{}",mimeType);
//            	throw new BadRequestAlertException("不符合的文件类型", "出现系统错误", "999");
//            }
//        } catch (Exception  e) {
//        	throw new BadRequestAlertException("验证文件类型时出现错误\n"+e.getMessage(), "出现系统错误", "999");
//        }
//    }
//
////    /**
////	 * 该方式支持本地文件，也支持http/https远程文件
////	 * @param fileUrl
////	 */
////	public static String getContentType(String fileUrl) {
////		String contentType = null;
////        try {
////        	contentType = new MimetypesFileTypeMap().getContentType(new File(fileUrl));
////        } catch (Exception e) {
////            log.debug("getContentType, File ContentType is : " + contentType);
////            log.debug("error in getContentType.", e);
////        }
////        return contentType;
////	}
//
//	/**
//     * 加载文件
//     * @param fileName 文件名
//     * @return 文件
//     */
//    public Resource loadFileAsResource(String fileName) {
//        try {
//            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
//            Resource resource = new UrlResource(filePath.toUri());
//            if(resource.exists()) {
//                return resource;
//            } else {
//            	throw new BadRequestAlertException("无法加载文件", "出现系统错误", "999");
//            }
//        } catch (MalformedURLException ex) {
//        	throw new BadRequestAlertException("出现异常\n"+ex.getMessage(), "出现系统错误", "999");
//        }
//    }
//
//    /**
//     * 获取mimeType
//     * @param file
//     * @return
//     */
//    public String getMimeType(MultipartFile file) {
//
//    	String mimeType = file.getContentType();
//    	log.debug("file.getContentType() is {}", file.getContentType());
//    	if(mimeType == null || (mimeType != null && mimeType.equalsIgnoreCase(MIME_TYPE_MULTI))) {
//    		try {
//				mimeType = MimeTypeUtil.getMimeType(file.getInputStream());
//				log.debug("MimeTypeUtil.getMimeType is {}", mimeType);
//			} catch (IOException e) {
//				log.error("error on read file");
//			}
//    	}
//
//    	return mimeType;
//    }
//
//    private String getExt(String fileName) {
//        int idx = fileName.lastIndexOf(".");
//        if (idx < 0) {
//            return "";
//        }
//        return fileName.substring(idx);
//    }
//
//}
